// @ts-ignore
import {defineAction} from "astro:actions";
import {z} from 'astro:schema';
import {addBlog, addBlogComment, type Blog, editBlog} from "@/service/BlogService.ts";
import {addMessage} from "@/service/ContactService.ts";

const contact_message = defineAction({
    accept: 'form',
    input: z.object({
        name: z.string(),
        email: z.string().email(),
        subject: z.string(),
        message: z.string()
    }),
    handler: async (message: {name: string, email: string, subject: string, message: string}) => {
        return await addMessage(message)
    },
})
const blog_edit = defineAction({
    accept: 'form',
    input: z.object({
        id: z.number().nullable(),
        title: z.string(),
        author: z.string(),
        createTime: z.string().datetime().nullable(),
        updateTime: z.string().datetime().nullable(),
        summary: z.string(),
        image: z.string(),
        content: z.string(),
    }),
    handler: async (blog: {id: number, title: string, author: string, createTime: string, updateTime: string, summary: string, image: string, content: string}) => {
        let b: Blog = {
            id: blog.id,
            title: blog.title,
            author: blog.author,
            createTime: new Date(blog.createTime),
            updateTime: blog.updateTime ? new Date(blog.updateTime) : undefined,
            summary: blog.summary,
            image: blog.image,
            content: blog.content,
        }
        return blog.id ? await editBlog(b) : await addBlog(b)
    },
})

const blog_comment = defineAction({
    accept: 'form',
    input: z.object({
        blogId: z.number(),
        message: z.string(),
    }),
    handler: async ({blogId, message}: { blogId: number, message: string }) => {
        return await addBlogComment(blogId, message, "Anonymous")
    },
})
export const server = {
    contact_message,
    blog_comment,
    blog_edit
}